package com.changeover.gwt.client.controller;

import com.changeover.gwt.client.event.ILoginViewEventHandler;
import com.changeover.gwt.client.event.LoginViewEvent;
import com.changeover.gwt.client.view.impl.LoginView;
import com.changeover.gwt.client.view.impl.MainView;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasWidgets;

public class ViewsController implements Controller {

    private enum GoToViewType {
        LOGIN_VIEW, TASK_VIEW;
    }

    private final HandlerManager eventBus;
    private HasWidgets container;

    @Override
    public void go(HasWidgets container) {
        this.container = container;
        managePresenter(GoToViewType.LOGIN_VIEW);
    }

    public ViewsController(HandlerManager eventBus) {
        this.eventBus = eventBus;
        bind();
    }

    private void bind() {

        // Register all the handlers
        eventBus.addHandler(LoginViewEvent.TYPE, new ILoginViewEventHandler() {
            @Override
            public void onLogined(LoginViewEvent event) {
                managePresenter(GoToViewType.TASK_VIEW);
            }
        });
        
    }

    private void managePresenter(GoToViewType actionType) {
        if (actionType != null) {
            Controller presenter = null;
            switch (actionType) {
            case LOGIN_VIEW:
                presenter = new LoginController(eventBus, new LoginView());
                break;
            case TASK_VIEW:
                presenter = new TasksController(eventBus, new MainView());
                break;
            }
            if (presenter != null) {
                presenter.go(container);
            }
        }
    }

}
